package com.test.daily.leetcode.y2022.m07.day0704.v06;

import java.util.HashMap;

/**
 * Solution
 *
 * @author Tom on 2022/7/4
 */
public class Solution {
    HashMap<Integer, Integer> map;
    public int kTimes(int[] arr, int K, int M){
        if(map == null){
            mapCreator(map);
        }
        int[] digits = new int[32];
        for(int num: arr){
            while(num != 0){
                int rightest = num &(-num);
                digits[map.get(rightest)]++;
                num ^= rightest;
            }
        }
        // 0~31位置上得到了1的个数
        int ans = 0;
        for (int i = 0; i < 32; i++) {
            if(digits[i] % M != 0){
                if(digits[i] % K == 0){
                    ans |= (1 << i); // 位运算需要
                }else {
                    return -1;
                }
            }
        }
        if(ans == 0){
            int count = 0;
            for(int num: arr){
                if(num == 0){
                    count++;
                }
            }
            if(count != K){
                return -1;
            }
        }
        return ans;
    }
    public void mapCreator(HashMap<Integer, Integer> map){
        int value = 1;
        for(int i = 0; i < 32; i++){
            map.put(value,i);
            value <<= 1;
        }
    }
}
